<template>
  <el-dialog :model-value="show" title="添加用户" @close="closeFn">
    <el-form ref="formRef" :rules="rules" :model="form" label-width="160px">
      <el-form-item label="账号" prop="username">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input v-model="form.nickName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          :disabled="id !== 0"
          v-model="form.password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input
          v-model="form.note"
          autocomplete="off"
          type="textarea"
          :rows="5"
        />
      </el-form-item>
      <el-form-item label="是否启用">
        <el-radio-group v-model="form.status">
          <el-radio :label="1" size="large">是</el-radio>
          <el-radio :label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button>取消</el-button>
        <el-button type="primary" @click="submit"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { reactive, ref, watch } from "vue";
import { getAdminInfoByIdApi, registerUserApi, updateUserInfoApi } from "@/api";
const formRef = ref<FormInstance | null>(null);
const props = defineProps({
  show: {
    type: Boolean,
  },
  id: {
    type: Number,
    default: 0,
  },
});

const form = reactive<FormAdmin>({
  id: 0,
  username: "",
  nickName: "",
  email: "",
  password: "",
  note: "",
  status: 1,
});

const passwordValidate = (
  rule: any,
  value: string,
  cb: (err?: string | Error) => void
) => {
  if (!value) {
    return cb(new Error("密码不能为空"));
  }
  // if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z.]{6,220}$/.test(value)) {
  //   return cb(new Error("密码的格式必须包含数字和字母"));
  // }
  cb();
};

const rules = reactive<FormRules<FormAdmin>>({
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    // { min: 6, max: 20, message: "密码的长度在6-20位之间", trigger: "blur" },
    {
      validator: passwordValidate,
      trigger: "blur",
    },
  ],
});

const emit = defineEmits(["close"]);

// 当id变化时
watch(
  () => props.id,
  () => {
    // 在编辑的时候才发请求
    if (props.id !== 0) {
      // 点击父组件的编辑按钮的时候，获取到对应的id，通过父传子，进入 当前组件
      getAdminInfoByIdApi(props.id).then((res) => {
        if (res.code === 200) {
          // 把旧数据渲染到表单
          Object.assign(form, res.data);
          // 上下两行代码作用一致
          // for(let key in res.data) {
          //   form[key] = res.data[key]
          // }
        }
      });
    }
  }
);

const submit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm("确定要添加庐用户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          if (props.id === 0) {
            // 向服务器发请求
            registerUserApi(form).then((res) => {
              if (res.code === 200) {
                ElMessage.success("添加成功");
                // 重置表单里面的数据
                formRef.value?.resetFields();
                // 更新表格数据
                emit("close", true);
              }
            });
          } else {
            // 发修改的请求
            updateUserInfoApi(form).then((res) => {
              if (res.code === 200) {
                ElMessage.success("修改成功");
                // 重置表单里面的数据
                formRef.value?.resetFields();
                // 更新表格数据
                emit("close", true);
              }
            });
          }
        })
        .catch(() => {});
    }
  });
};

const closeFn = () => {
  emit("close");
  // 清空表单
  formRef.value?.resetFields();
};
</script>
<style lang="less" scoped></style>
